package com.luli.controllor;

import com.alibaba.fastjson.JSON;
import com.luli.entity.Person;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 陆离
 * 2024/11/29
 */
public class QueryResultQuerying {
    public static void main(String[] args) {
        // 创建一个包含Person对象的List
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 25, "Female"));
        personList.add(new Person("Bob", 30, "Male"));
        personList.add(new Person("Charlie", 20, "Male"));
        personList.add(new Person("David", 20, "Male"));

        // 模拟传入的可能为空的查询参数
        String nameParam = "";
        Integer ageParam = 20;
        String genderParam = "Male";

        // 对查询结果进行查询操作
        List<Person> resultList = queryResult(personList, nameParam, ageParam, genderParam);
        System.out.println(JSON.toJSONString(resultList));
        List<String> objects = new ArrayList<>();
        for (Person person : resultList) {
            objects.add(person.getName());
        }
        for (int i = 0; i < personList.size(); i++) {
            for (String object : objects) {
                if (!personList.get(i).getName().equals(object)){
                    personList.remove(i);
                }
            }
        }
        System.out.println("满足条件的人员列表：");
        personList.forEach(System.out::println);
    }

    // 执行对查询结果的查询操作
    private static List<Person> queryResult(List<Person> personList, String nameParam, Integer ageParam, String genderParam) {
        // 构建用于筛选的Predicate列表
        List<Predicate<Person>> predicates = new ArrayList<>();

        // 如果nameParam不为空，添加相应的筛选条件
        if (nameParam != null) {
            predicates.add(person -> person.getName().equals(nameParam));
        }

        // 如果ageParam不为空，添加相应的筛选条件
        if (ageParam != null) {
            predicates.add(person -> person.getAge() == ageParam);
        }

        // 如果genderParam不为空，添加相应的筛选条件
        if (genderParam != null) {
            predicates.add(person -> person.getGender().equals(genderParam));
        }

        // 如果没有添加任何条件，返回原始的List
        if (predicates.isEmpty()) {
            return personList;
        }

        // 使用and方法组合所有条件Predicate
        Predicate<Person> combinedPredicate = predicates.stream().reduce(Predicate::and).get();
        // 使用组合后的Predicate对查询结果进行筛选
        return personList.stream().filter(combinedPredicate).collect(Collectors.toList());
    }



}
